<?php session_start();

require("db.php");
include("functions.php");

//$tyrant = new tyrant;

	$user = filter_var($_POST['user'], FILTER_SANITIZE_STRIPPED);
	$pass = $_POST['pass'];
	//$logged_in_user = $_SESSION['user'];

	//make sure the POST superglobal is indeed passing information...
	$testinfo = array(
		'user' => $_POST['user'],
		'pass' => $_POST['pass']
	);
	
	$logged_in_user = TRUE;

	if($user && $pass) {
	
		if($logged_in_user == $user) {
			//echo '<meta http-equiv="REFRESH" content="0;url=' . $base_url . 'dashboard.php>';
			//redirect('http://localhost/project_perso/dashboard.php');
			//redirect('dashboard.php');
			header('Location: dashboard.php');
			//echo "you're already logged in, man.. <a href='dashboard.php'>Go back</a>";
		} else {
			echo "please insert username and password.";
		}

		/*$db = mysql_connect("localhost", "root", "root");

		if(!$db) {
			die("Couldn't connect to the database man... Heres the details: " . mysql_error());
		}

		mysql_select_db("nexus", $db);*/
		
		//$result = mysql_query("SELECT * FROM users WHERE username = '{$user}' AND password = md5('{$pass}')");

		//REMINDER: USE CRYPT() INSTEAD
		$md5 = md5($pass);
		$result = $db->prepare("SELECT * FROM users WHERE username = :user AND password = :pass");

		$params = array(
			':user' => $user,
			':pass' => $md5
		);

		$result->setFetchMode(PDO::FETCH_OBJ);

		$result->execute($params);

		while($row = $result->fetch()) {

			//echo "Your credentials have been found.";
			//at this point, the user is authenticated because username and password match..
			$_SESSION['user_id'] = $row->id;
			$_SESSION['fname'] = $row->fname;
			$_SESSION['lname'] = $row->lname;
			$_SESSION['agency'] = $row->agency;
			$_SESSION['position'] = $row->position;
			
			redirect("dashboard.php");
			
		}

		if($result->fetch() == FALSE || $result->fetch() == NULL) {
				//echo "username and password dont exist.. <br />";
				redirect("login.php?err=1");
		}
		
		/*if($obj == FALSE) {
			echo "username and password dont exist.. <br />";
			//redirect("login.php");
		} else {
			
			//echo "Your credentials have been found.";
			//at this point, the user is authenticated because username and password match..
			$_SESSION['user_id'] = $obj->id;
			$_SESSION['fname'] = $obj->fname;
			$_SESSION['lname'] = $obj->lname;
			$_SESSION['agency'] = $obj->agency;
			$_SESSION['position'] = $obj->position;
			
			redirect("dashboard.php");
		}*/
		
		//this checks to see if information is valid..
		/*if($obj == FALSE) {
			echo "username and password dont exist.. <br />";
		} else {
			echo "<pre>";
				print_r($obj);
			echo "</pre>";
		}*/
		
	} else {
		echo '<meta http-equiv="REFRESH" content="0;url=' . $base_url . 'login.php';
		//redirect("login.php");
	}


?>